<template>
  <div class="wrap-container">
    <div class="order_detail">
      <div class="order_l">
        <div class="order_top">
          <div class="manage_tit">
            <div class="line"></div>
            <p>订单场馆信息</p>
          </div>
          <div style="display: flex; align-items: center">
            <div class="order_top_r">
              <p>订单状态</p>
              <span class="order_status" v-if="details.orderFlag == 1">待支付</span>
              <span class="order_status" v-if="details.orderFlag == 2">待核销</span>
              <span class="order_status" v-if="details.orderFlag == 3">待评价</span>
              <span class="order_status" v-if="details.orderFlag == 4">已取消</span>
              <span class="order_status" v-if="details.orderFlag == 5">已完成</span>
              <span class="order_status" v-if="details.orderFlag == 7">已退款</span>
              <span class="order_status" v-if="details.orderFlag == 8">待确认</span>
            </div>
            <div class="approval_btn">
              <el-button @click="goBack" size="small">返回</el-button>
            </div>
          </div>
        </div>
        <div class="order_item">
          <p class="order_tit">场馆详情</p>
          <div class="order_info">
            <div class="flex flex_box">
              <div>
                <div class="info_item">
                  <span class="info_label">订单编号：</span>
                  <span class="info_val">{{ details.orderNo }}</span>
                </div>
                <div class="info_item">
                  <span class="info_label">预约场馆：</span>
                  <span class="info_val">{{ details.stadiumName }}</span>
                </div>
              </div>
              <div>
                <div class="info_item">
                  <span class="info_label">订单日期：</span>
                  <span class="info_val">{{ details.paymentTime }}</span>
                </div>
                <div class="info_item">
                  <span class="info_label">场馆类型：</span>
                  <span class="info_val">{{ details.stadiumType }}</span>
                </div>
              </div>
              <div>
                <div class="info_item">
                  <span class="info_label">订单来源：</span>
                  <span class="info_val">{{ details.source || '微信小程序' }}</span>
                </div>
                <div class="info_item">
                  <span class="info_label">退款时限：</span>
                  <span class="info_val">开场前{{ details.cancelHours }}小时</span>
                </div>
              </div>
              <div>
                <div class="info_item">
                  <span class="info_label">所在区域：</span>
                  <span class="info_val">{{ details.areaName }}</span>
                </div>
                <div class="info_item">
                  <span class="info_label">提前核销时间：</span>
                  <span class="info_val">开场前{{ details.writeMinutes }}分钟</span>
                </div>
              </div>
              <div>
                <div class="info_item flex">
                  <span class="info_label">营业时间：</span>
                  <div class="info_val">
                    <p>工作日：{{ details.workTime }}</p>
                    <p>节假日：{{ details.legalTime }}</p>
                  </div>
                </div>
              </div>
            </div>
            <div class="info_item flex">
              <span class="info_label">订单备注：</span>
              <p class="order_remark">{{ details.orderRemarks || '无' }}</p>
            </div>
          </div>
        </div>
        <div class="order_item">
          <p class="order_tit">预约详情</p>
          <div class="order_table">
            <el-table :data="reservateList" border :span-method="objectSpanMethod">
              <el-table-column label="预约日期" prop="dateFormat" align="center" />
              <el-table-column label="预约场地" prop="siteName" align="center">
                <template #default="{ row }">
                  <span>{{ row.isIndependence == 0 ? row.siteName : '散客场' }}</span>
                  <div class="flex justify-center site_style">
                    <p>{{ row.isStandard == 0 ? '标准场' : '非标准场' }}</p>
                    <p>{{ row.siteNature == 0 ? '全场' : '半场' }}</p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="预约时段" prop="times" align="center" />
              <el-table-column label="场地状态" prop="siteType" align="center" />
              <el-table-column label="单价金额（元）" prop="price" align="center" />
            </el-table>
          </div>
        </div>
        <div class="order_item">
          <p class="order_tit">优惠券及支付详情</p>
          <div class="order_table">
            <el-table :data="payInfo" border :span-method="objectSpanMethod2">
              <el-table-column label="订单金额（元）" prop="orderMoney" align="center" />
              <el-table-column label="优惠券类型" prop="couponType" align="center">
                <template #default="{ row }">
                  <span v-if="row.discountType == null">--</span>
                  <span v-else-if="row.discountType == 1">抵扣券</span>
                  <span v-else-if="row.discountType == 2">全免券</span>
                  <span v-else-if="row.discountType == 3">满减券</span>
                </template>
              </el-table-column>
              <el-table-column label="优惠券明细" prop="paymentAmount" align="center">
                <template #default="{ row }">
                  <span v-if="row.discountType == null">--</span>
                  <span v-else-if="row.discountType == 1">抵扣金额{{ row.discountAmount }}元</span>
                  <span v-else-if="row.discountType == 2">本次费用全免</span>
                  <span v-else-if="row.discountType == 3"
                    >满{{ row.totalLimit }}减{{ row.discountAmount }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column label="实付金额（元）" prop="paymentMoney" align="center" />
              <el-table-column label="支付方式" prop="paymentType" align="center" />
            </el-table>
          </div>
        </div>
        <div class="order_item" v-if="userInfo">
          <p class="order_tit">用户信息</p>
          <div class="order_info user_info">
            <div class="info_item">
              <span class="info_label">会员姓名：</span>
              <span class="info_val">{{ userInfo.realName }}</span>
            </div>
            <div class="info_item">
              <span class="info_label">联系手机：</span>
              <span class="info_val">{{ hidePhone(userInfo.phone) }}</span>
            </div>
            <div class="info_item">
              <span class="info_label">会员类型：</span>
              <span class="info_val">{{ details.memberType || '普通会员' }}</span>
            </div>
            <div class="info_item">
              <span class="info_label">下单数量：</span>
              <span class="info_val">{{ userInfo.countOrder }}</span>
            </div>
            <div class="info_item" v-hasPermi="['sys:order:total_fee']">
              <span class="info_label">累计消费：</span>
              <span class="info_val">{{ userInfo.sumMoney || 0 }}（元）</span>
            </div>
            <div class="info_item">
              <span class="info_label">性别：</span>
              <span class="info_val">{{ userInfo.sex }}</span>
            </div>
            <div class="info_item" v-hasPermi="['sys:order:idcard']">
              <span class="info_label">身份证号：</span>
              <span class="info_val">--</span>
            </div>
            <!-- <div class="info_item">
              <span class="info_label">会员类型：</span>
              <span class="info_val">{{ details.memberType }}</span>
            </div>
            <div class="info_item">
              <span class="info_label">会员等级：</span>
              <span class="info_val">{{ details.memberLevel }}</span>
            </div> -->

            <!-- <div class="info_item">
              <span class="info_label">累计积分：</span>
              <span class="info_val">--</span>
            </div> -->
          </div>
        </div>
        <div class="order_customer" v-hasPermi="['sys:order:customer_view']">
          <p class="order_tit">客诉处理</p>
          <div class="flex handle_input">
            <span class="text-sm">问题描述</span>
            <div class="w-full flex-1 ml-6">
              <editor
                v-model="issueContent"
                :min-height="108"
                :placeholderTxt="'在此输入客户反馈的问题描述'"
              />
            </div>

            <!-- <el-input
              type="textarea"
              :rows="4"
              placeholder="在此输入客户反馈的问题描述"
              v-model="issueContent"
            ></el-input> -->
          </div>
          <div class="flex justify-end save_customer">
            <el-button type="primary" @click="saveDispose">保存</el-button>
          </div>
          <p class="order_tit">处理详情</p>
          <div class="order_table">
            <el-table :data="disposeList" border>
              <el-table-column label="客户诉求" align="center">
                <template #default="{ row }">
                  <div v-html="row.issueContent"></div>
                </template>
              </el-table-column>
              <el-table-column label="处理时间" prop="disposeTime" align="center" width="200" />
              <el-table-column label="处理进度" prop="times" align="center" width="300">
                <template #default="{ row }">
                  <span v-if="!row.isEdit">{{ row.disposePlan }}</span>
                  <el-input v-model="row.disposePlan" v-else></el-input>
                </template>
              </el-table-column>
              <el-table-column label="处理结果" prop="disposeResult" align="center" width="300">
                <template #default="{ row }">
                  <span v-if="!row.isEdit">{{ row.disposeResult }}</span>
                  <el-input v-model="row.disposeResult" v-else></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作员" prop="createUser" align="center" width="120" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button type="text" @click="handleAdd(scope.row)">添加</el-button>
                  <el-button type="text" @click="handleEdit(scope.row)" v-if="!scope.row.isEdit"
                    >编辑</el-button
                  >
                  <el-button type="text" @click="saveDisposeRow(scope.row)" v-if="scope.row.isEdit"
                    >保存</el-button
                  >
                  <el-button
                    type="text"
                    @click="handleDel(scope.row.id, scope.$index)"
                    class="cancel_txt"
                    >取消</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="items_center sure_btn">
          <el-button type="primary" @click="goStadiumDetail">确认订单入口</el-button>
        </div>
      </div>
      <div class="order_r" v-if="details.orderFlag == 5">
        <div :class="['code_box', { disabled: details.orderFlag == 5 }]">
          <p class="code_label">场馆核验码</p>
          <p class="code_val">{{ details.verificationCode || '— —' }}</p>
        </div>
        <!-- <div class="order_track">
          <div class="order_top">
            <div class="manage_tit">
              <div class="line"></div>
              <p>订单追踪</p>
            </div>
          </div>
          <div class="track_list">
            <div class="track_item">
              <p class="create_time">2025-04-25 15:53:05</p>
              <p class="track_cont">
                用户<span>李建刚</span><span>创建订单</span>
              </p>
            </div>
            <div class="track_item">
              <p class="create_time">2025-04-25 15:53:05</p>
              <p class="track_cont">
                用户<span>李建刚</span><span>取消支付</span>
              </p>
              <p>操作员：客服 张老三</p>
            </div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElInput } from 'element-plus'
import { debounce } from 'lodash'
import {
  getOrderDetail,
  getAppointmentList,
  getUserData,
  getOrderDisposeList,
  saveOrderDispose,
  delOrderDispose,
} from '@/api/order/order.js'
import { checkPermi } from '@/utils/permission'
import { useStore } from 'vuex'

defineOptions({
  name: 'OrderDetail',
})

interface Details {
  orderFlag?: number
  orderNo?: string
  stadiumName?: string
  paymentTime?: string
  stadiumType?: string
  source?: string
  cancelHours?: number
  areaName?: string
  writeMinutes?: number
  workTime?: string
  legalTime?: string
  orderRemarks?: string
  userId?: number
  memberType?: string
  stadiumId?: number
  orderTime?: string
  verificationCode?: string
}

interface Reservation {
  dateFormat: string
  siteName: string
  times: string
  siteType: string
  price: number
  isIndependence: number
  isStandard: number
  siteNature: number
}

interface PayInfo {
  orderMoney: number
  couponType: string
  paymentAmount: number
  paymentMoney: number
  paymentType: string
  discountType: number | null
  discountAmount: number
  totalLimit: number
}

interface UserInfo {
  realName: string
  phone: string
  countOrder: number
  sumMoney: number
  sex: string
}

interface DisposeItem {
  id: number | null
  issueContent: string
  createUser: string
  createUserId: number
  isEdit: boolean
  disposePlan?: string
  disposeResult?: string
  disposeTime?: string
  times?: string
}

const route = useRoute()
const router = useRouter()
const store = useStore()

const orderId = ref<string | null>(null)
const details = ref<Details>({})
const reservateList = ref<Reservation[]>([]) //预约列表
const userInfo = ref<UserInfo | null>(null) //订单用户信息
const payInfo = ref<PayInfo[]>([])
const handleList = ref<never[]>([])
const spanArr = ['dateFormat', 'siteName']
const spanObj = ref<Record<string, number[]>>({})
const spanArr2 = ['orderMoney', 'paymentMoney', 'paymentType']
const spanObj2 = ref<Record<string, number[]>>({})
const disposeList = ref<DisposeItem[]>([])
const issueContent = ref('')

// 获取订单详情
const getData = async () => {
  if (!orderId.value) return
  try {
    const { data } = await getOrderDetail(orderId.value)
    details.value = data
    getUserDataFunc()
  } catch (error) {
    console.error(error)
  }
}

// 获取预约列表
const getReservateList = async () => {
  if (!orderId.value) return
  try {
    const { data } = await getAppointmentList(orderId.value)
    payInfo.value = data.orderCouponList
    reservateList.value = data.orderDetailList
    getSpanArr(reservateList.value)
    getSpanArr2(payInfo.value)
  } catch (error) {
    console.error(error)
  }
}

// 预约详情合并单元格
const getSpanArr: Fn = (data: Reservation[]) => {
  spanArr.forEach((key) => {
    let count = 0
    spanObj.value[key] = []
    data.forEach((item, index) => {
      if (index === 0) {
        if (spanObj.value[key]) {
          spanObj.value[key].push(1)
        }
      } else {
        const prevItem = data[index - 1]
        const currentItem = item
        if (prevItem) {
          const prevValue = prevItem[key as keyof Reservation]
          const currentValue = currentItem[key as keyof Reservation]

          if (currentValue === prevValue) {
            if (spanObj.value[key] && spanObj.value[key][count] !== undefined) {
              spanObj.value[key][count] = (spanObj.value[key][count] || 0) + 1
            }
            if (spanObj.value[key]) {
              spanObj.value[key].push(0)
            }
          } else {
            count = index
            if (spanObj.value[key]) {
              spanObj.value[key].push(1)
            }
          }
        }
      }
    })
  })
}

const objectSpanMethod: Fn = ({ row, column, rowIndex, columnIndex }: any) => {
  if (column.property == 'dateFormat' || column.property == 'siteName') {
    const property = column.property
    if (spanObj.value[property] && spanObj.value[property][rowIndex] !== undefined) {
      const value = spanObj.value[property]?.[rowIndex] ?? 0
      return [value, 1]
    } else {
      return [0, 0]
    }
  }
}

// 预约详情合并单元格
const getSpanArr2 = (data: PayInfo[]) => {
  spanArr2.forEach((key) => {
    let count = 0
    spanObj2.value[key] = []
    data.forEach((item, index) => {
      if (index === 0) {
        if (spanObj2.value[key]) {
          spanObj2.value[key].push(1)
        }
      } else {
        const prevItem = data[index - 1]
        const currentItem = item
        if (prevItem) {
          const prevValue = prevItem[key as keyof PayInfo]
          const currentValue = currentItem[key as keyof PayInfo]

          if (currentValue === prevValue) {
            if (spanObj2.value[key] && spanObj2.value[key][count] !== undefined) {
              spanObj2.value[key][count] = (spanObj2.value[key][count] || 0) + 1
            }
            if (spanObj2.value[key]) {
              spanObj2.value[key].push(0)
            }
          } else {
            count = index
            if (spanObj2.value[key]) {
              spanObj2.value[key].push(1)
            }
          }
        }
      }
    })
  })
}

const objectSpanMethod2: Fn = ({ row, column, rowIndex, columnIndex }: any) => {
  if (
    column.property == 'orderMoney' ||
    column.property == 'paymentMoney' ||
    column.property == 'paymentType'
  ) {
    const property = column.property
    if (spanObj2.value[property] && spanObj2.value[property][rowIndex] !== undefined) {
      const value = spanObj2.value[property]?.[rowIndex] ?? 0
      return [value, 1]
    } else {
      return [0, 0]
    }
  }
}

// 获取订单用户信息
const getUserDataFunc = async () => {
  if (details.value.userId) {
    try {
      const { data } = await getUserData(details.value.userId)
      userInfo.value = data
    } catch (error) {
      console.error(error)
    }
  }
}

// 跳转到场馆详情
const goStadiumDetail = () => {
  if (!details.value.orderTime || !details.value.stadiumId || !details.value.stadiumType) return
  const date = details.value.orderTime.substring(0, 10)
  const type = details.value.stadiumType
  router.push({
    path: '/stadium/detail',
    query: { id: details.value.stadiumId.toString(), date, type },
  })
}

// 获取客户诉求列表
const getDispose = async () => {
  if (!orderId.value) return
  try {
    const { data } = await getOrderDisposeList({ orderId: orderId.value })
    disposeList.value = data.map((item: any) => ({
      ...item,
      isEdit: false,
    }))
  } catch (error) {
    console.error(error)
  }
}

// 添加客户诉求处理
const handleAdd = (row: DisposeItem) => {
  if (disposeList.value.some((item) => item.isEdit == true)) {
    ElMessage.error('请先保存编辑中的数据')
    return
  }
  disposeList.value.push({
    id: null,
    issueContent: row.issueContent,
    createUser: store.state.user.name,
    createUserId: store.state.user.id,
    isEdit: true,
  })
}

// 编辑客户诉求处理
const handleEdit = (row: DisposeItem) => {
  const index = disposeList.value.findIndex((item) => item === row)
  if (index !== -1) {
    if (disposeList.value[index]) disposeList.value[index].isEdit = true
  }
}

// 保存客户诉求
const saveDispose = debounce(
  async () => {
    if (!orderId.value) return
    try {
      const params = {
        orderId: orderId.value,
        issueContent: issueContent.value,
        createUser: store.state.user.name,
        createUserId: store.state.user.id,
      }
      if (!params.issueContent) {
        ElMessage.error('请输入问题描述')
        return
      }
      const res = await saveOrderDispose(params)
      ElMessage.success(res.msg)
      issueContent.value = ''
      getDispose()
    } catch (e) {
      ElMessage.error((e as Error)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 保存客户诉求行
const saveDisposeRow = debounce(
  async (row: DisposeItem) => {
    if (!orderId.value) return
    try {
      const params = {
        orderId: orderId.value,
        issueContent: row.issueContent,
        createUser: store.state.user.name,
        createUserId: store.state.user.id,
        id: row.id,
        disposePlan: row.disposePlan,
        disposeResult: row.disposeResult,
      }
      if (!params.issueContent) {
        ElMessage.error('请输入问题描述')
        return
      }
      const res = await saveOrderDispose(params)
      ElMessage.success(res.msg)
      getDispose()
    } catch (e) {
      ElMessage.error((e as Error)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 删除客户诉求处理
const handleDel = (id: number | null, index: number) => {
  if (id != null) {
    ElMessageBox.confirm('是否确认删除选中的数据项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          await delOrderDispose(id)
          disposeList.value.splice(index, 1)
          ElMessage.success('删除成功')
        } catch (error) {
          console.error(error)
        }
      })
      .catch(() => {})
  } else {
    disposeList.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 手机号中间*号
const hidePhone = (phonenumber: string) => {
  if (checkPermi(['sys:order:btn_show_phone'])) {
    return phonenumber
  } else {
    return phonenumber.substring(0, 3) + '****' + phonenumber.substring(7, 11)
  }
}

onMounted(() => {
  orderId.value = (route.query.id as string) || null
  getData()
  getReservateList()
  getDispose()
})
</script>

<style lang="scss" scoped>
.order_detail {
  display: flex;
  .order_l {
    background: #fff;
    padding: 15px;
    // height: calc(100vh - 80px);
    flex: 1;
    width: 100%;
  }
  .order_item {
    margin-bottom: 32px;
    margin-left: 12px;
    padding-bottom: 41px;
    border-bottom: 1px solid #e5e5e5;
  }
  .order_tit {
    font-size: 14px;
    line-height: 21px;
    margin-bottom: 13px;
  }
  .order_top {
    display: flex;
    justify-content: space-between;
    height: 33px;
    margin-bottom: 20px;
    .order_top_r {
      display: flex;
      align-items: flex-end;
      p {
        font-size: 16px;
        line-height: 24px;
      }
      span {
        color: #2590fa;
        font-size: 14px;
        line-height: 21px;
      }
      .order_status {
        font-size: 22px;
        line-height: 32px;
        margin-left: 26px;
      }
      img {
        width: 15px;
        height: 15px;
        margin-right: 7px;
      }
    }
  }
  .order_info {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .flex_box {
      .info_item {
        margin-bottom: 16px;
      }
    }
    .info_item {
      // width: 20%;
      margin-right: 65px;
      font-size: 14px;
      min-width: 160px;
      .info_label {
        color: #808080;
        margin-right: 10px;
        line-height: 21px;
      }
      .info_val {
        line-height: 21px;
      }
      .order_remark {
        padding: 14px 12px;
        border: 1px solid #a6a6a6;
        width: 859px;
        min-height: 89px;
        line-height: 21px;
        box-sizing: border-box;
      }
    }
  }
  .order_table {
    padding: 0 11px 0 0;
    :deep(.el-table) {
      th {
        height: 36px;
        padding: 0;
      }
      th,
      td {
        font-size: 14px;
      }
      .el-button {
        padding: 0;
        &.cancel_txt {
          color: #383838;
        }
      }
      .site_style {
        p {
          width: 55px;
          height: 25px;
          text-align: center;
          line-height: 25px;
          background: rgba(9, 136, 251, 0.11);
          color: #0988fb;
          font-size: 12px;
          border-radius: 6px;
          margin-top: 4px;
          & + p {
            margin-left: 7px;
          }
        }
      }
      .el-input__inner {
        text-align: center;
        color: #383838;
      }
    }
  }
  .order_customer {
    .handle_input {
      padding-right: 11px;
      span {
        color: #808080;
      }
      .el-textarea {
        flex: 1;
        margin-left: 23px;
      }
      :deep(.el-textarea__inner) {
        background: #f3f4f6;
        color: #808080;
        font-size: 14px;
        line-height: 21px;
        border: none;
        resize: none;
        color: #383838;
        border: 1px solid #e5e5e5;
        font-family: Microsoft YaHei;
      }
    }
    .save_customer {
      padding-right: 11px;
      margin-top: 13px;
      .el-button {
        width: 80px;
        height: 33px;
        padding: 0;
        line-height: 33px;
        border-radius: 6px;
      }
    }
  }
  .order_r {
    flex: 1;
    margin-left: 15px;
    .code_box {
      width: 384px;
      height: 148px;
      background: linear-gradient(225deg, #2a82e4 0%, #015aff 100%);
      border-radius: 11px;
      color: #fff;
      overflow: hidden;
      font-weight: bold;
      &.disabled {
        background: #e5e5e5;
      }
      .code_label {
        font-size: 18px;
        text-align: center;
        line-height: 27px;
        margin-top: 20px;
      }
      .code_val {
        font-size: 60px;
        line-height: 71px;
        margin-top: 15px;
        text-align: center;
      }
    }
    .order_track {
      background: #fff;
      margin-top: 15px;
      padding: 10px 16px;
      height: 100%;
      .order_top {
        margin-bottom: 0;
      }
      .track_list {
        padding: 11px 12px 0;
        .track_item {
          margin-bottom: 15px;
          .create_time {
            color: #808080;
            line-height: 18px;
          }
          .track_cont {
            line-height: 21px;
            margin: 2px 0;
            span {
              margin: 0 8px;
            }
            .green {
              color: #00baad;
            }
            .red {
              color: #d43030;
            }
            .primary {
              color: #2a82e4;
            }
          }
        }
      }
    }
  }
  .user_info {
    row-gap: 21px;
    .info_item {
      width: 20%;
      margin-right: 0;
    }
  }
  .sure_btn {
    margin-top: 41px;
    padding-bottom: 30px;
  }
}
:deep(.ql-toolbar) {
  display: none;
}
:deep(.ql-container.ql-snow) {
  width: 100%;
  border: 1px solid #e5e5e5 !important;
  background: #f3f4f6;
  border-radius: 6px;
  .ql-editor {
    &::before {
      font-style: normal;
    }
  }
}
.approval_btn {
  margin-left: 30px;
}
</style>
